package compile;

import java.util.*;

public class ExprParser {
    private String input;
    private Map<Character, Set<Character>> firstVt = new HashMap<>();

    public ExprParser(String input) {
        this.input = input;
    }

    public Map<Character, Set<Character>> getFirstVt() {
        return firstVt;
    }

    public void constructFirstVt() {
        String[] lines = input.split("\n");
        for (String line : lines) {
            char left = line.charAt(0);
            String[] rights = line.substring(3).split("\\|");
            for (String right : rights) {
                char[] symbols = right.toCharArray();
                if (symbols.length > 0) {
                    if (!Character.isUpperCase(symbols[0])) {
                        addToFirstVt(left, symbols[0]);
                    }
                    for (int i = 0; i < symbols.length - 1; i++) {
                        if (!Character.isUpperCase(symbols[i]) && Character.isUpperCase(symbols[i + 1])) {
                            addToFirstVt(left, symbols[i + 1]);
                        }
                        if (existEpsilonFirstVt(symbols[i])) {
                            if (!Character.isUpperCase(symbols[i + 1])) {
                                addToFirstVt(left, symbols[i + 1]);
                            }
                            if (i == symbols.length - 2 && existEpsilonFirstVt(symbols[i + 1])) {
                                addToFirstVt(left, '_');
                            }
                        }
                    }
                }
            }
        }
    }

    private void addToFirstVt(char left, char right) {
        if (!firstVt.containsKey(left)) {
            firstVt.put(left, new HashSet<>());
        }
        firstVt.get(left).add(right);
    }

    private boolean existEpsilonFirstVt(char symbol) {
        return symbol == '_';
    }
}
